package cn.wit.backen.service.impl;

import cn.wit.backen.condition.LoginCondition;
import cn.wit.backen.mapper.SysUserMapper;
import cn.wit.backen.service.LoginService;
import cn.wit.backen.vo.LoginVO;
import cn.wit.utils.pojo.SysUser;
import cn.wit.utils.response.Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public Result login(LoginCondition condition) {
        log.info(condition.toString());
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq("username", condition.getUsername());
        SysUser user = sysUserMapper.selectOne(wrapper);
        if (user == null) {
            return Result.error("登录失败");
        }
        if (condition.getPassword().equals(user.getPassword())) {
            String token = user.getId().toString() + UUID.randomUUID().toString() + user.getId();
            redisTemplate.opsForValue().set(token, user);
            LoginVO loginVO = new LoginVO();
            loginVO.setToken(token);
            loginVO.setUsername(condition.getUsername());
            return Result.ok(loginVO);
        }
        return Result.error("登录失败");
    }

    @Override
    public Result logout(String token) {
        redisTemplate.delete(token);
        return Result.ok();
    }

    @Override
    public Result updatePwd(String username, String oldPassword, String newPassword) {
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        SysUser user = sysUserMapper.selectOne(wrapper);
        if (user == null) {
            return Result.error("修改密码失败");
        }
        if (oldPassword.equals(user.getPassword())) {
            SysUser sysUser = new SysUser();
            sysUser.setId(user.getId());
            sysUser.setPassword(newPassword);
            sysUserMapper.updateById(sysUser);
        }
        return Result.ok("修改密码成功");
    }


}
